//
//  KABMallClassifyVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/22.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallClassifyVC.h"
#import "KABMallClassifyTCell.h"
#import "KABMallClassifyCCell.h"
#import "KABMallClassifyShopCCell.h"
#import "KABMallClaListVC.h"
#import "GlobalHeader.h"
#import "XDAFNetworking.h"
#import "MBProgressHUD+XDPrompt.h"
#import "ApiManager.h"
#import "KABModel.h"
#import <MJRefresh.h>
#import "KABMallMyShopVC.h"
#import <UIScrollView+EmptyDataSet.h>

@interface KABMallClassifyVC ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (readonly, nonatomic) KABMallProductType *proType;
@property (readonly, nonatomic) KABMallProTypeItem *curSubProType;
@property (assign,   nonatomic) NSInteger selProTypeIndex;  //!< 一级分类选中的index
@end

static NSString *const kTViewCellId = @"KABMallClassifyTCell";
static NSString *const kCViewCellId = @"KABMallClassifyCCell";
static NSString *const kCViewShopCellId = @"KABMallClassifyShopCCell";
static NSInteger const kRequestShopListSize = 20;

@implementation KABMallClassifyVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"全部分类";
    
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editBarBtnTapped:)];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分类" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initSubViews {
    self.automaticallyAdjustsScrollViewInsets = NO;
    //
    //    self.tableView.contentInset = UIEdgeInsetsMake(-64 * 2.0, 0, 49.0, 0);
    //    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 49.0, 0);
    
    UINib *cellNib = [UINib nibWithNibName:kTViewCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kTViewCellId];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = 52.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = NO;
    
    UINib *cvCellNib = [UINib nibWithNibName:kCViewCellId bundle:nil];
    [self.collectionView registerNib:cvCellNib forCellWithReuseIdentifier:kCViewCellId];
    UINib *cvShopCellNib = [UINib nibWithNibName:kCViewShopCellId bundle:nil];
    [self.collectionView registerNib:cvShopCellNib forCellWithReuseIdentifier:kCViewShopCellId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.emptyDataSetSource = self;
    // 下拉刷新
    self.collectionView.mj_header = self.mj_header;
    self.collectionView.mj_footer = self.mj_footer;
    
    [self requestProductType];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"什么都没有喔" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.proType.product_type_list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABMallClassifyTCell *cell = [tableView dequeueReusableCellWithIdentifier:kTViewCellId forIndexPath:indexPath];
    KABMallProTypeItem *item = self.proType.product_type_list[indexPath.row];
    cell.nameLabel.text = item.content;
    return cell;
}

#pragma mark - UITableViewDelegate
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    KABMallShoCarHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
//    return view;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    KABMallSurOrdFooterHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kFooterViewId];
//    return view;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 0.1;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return 6.0;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.selProTypeIndex = indexPath.row;
    [self requestProSubTypeAndShopsWithHeader:YES];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return self.curSubProType.product_subtype_list.count;
    } else {
        return self.curSubProType.shop_list.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        KABMallClassifyCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCViewCellId forIndexPath:indexPath];
        if (indexPath.item < self.curSubProType.product_subtype_list.count) {
            [cell configViewWithSubTypeItem:self.curSubProType.product_subtype_list[indexPath.item]];
        }
        return cell;
    } else {
        KABMallClassifyShopCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCViewShopCellId forIndexPath:indexPath];
        if (indexPath.item < self.curSubProType.shop_list.count) {
            [cell configViewWithShopListItem:self.curSubProType.shop_list[indexPath.item]];
        }
        return cell;
    }
}

#pragma mark - <UICollectionViewDelegateFlowLayout>
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 110.0);
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CGFloat width = (CGRectGetWidth(self.view.bounds) - 75.0) / 3.0;
        CGFloat height = width * 140.0 / 100.0;
        return CGSizeMake(width, height);
    } else {
        CGFloat width = CGRectGetWidth(self.view.bounds) - 75.0;
        CGFloat height = width * 177.0 / 270.0;
        return CGSizeMake(width, height);
    }
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        KABMallClaListVC *vc = [[KABMallClaListVC alloc] init];
        KABMallProSubTyepItem *subItem = self.curSubProType.product_subtype_list[indexPath.item];
        vc.subType_id = subItem.subTypeId;
        vc.subTyep_content = subItem.content;
        vc.viewType = KABMallClaListVCTypeSubType;
        [self showViewController:vc sender:nil];
    } else {
        KABMallMyShopVC *vc = [[KABMallMyShopVC alloc] init];
        vc.shop_owner_id = self.curSubProType.shop_list[indexPath.item].shop_owner_id;
        [self showViewController:vc sender:nil];
    }
}

#pragma mark - event response
- (void)editBarBtnTapped:(UIBarButtonItem *)item {
}

//- (void)allPayBtnTapped:(UIButton *)btn {
//    KABMallSureOrderVC *vc = [[KABMallSureOrderVC alloc] init];
//    [self showViewController:vc sender:nil];
//}

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.curSubProType.totalLoad) {
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.collectionView.mj_footer resetNoMoreData];
    }
    
    // 选中第几个
    [self.tableView reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.selProTypeIndex inSection:0];
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    [self.collectionView reloadData];
}

- (void)collectionViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.collectionView.mj_header endRefreshing];
    } else {
        [self.collectionView.mj_footer endRefreshing];
    }
}

- (void)collectionViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestProSubTypeAndShopsWithHeader:isHeader];
}

#pragma mark - network request
- (void)requestProductType {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiProductType] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"商品分类返回：%@", responseObject);
        [hud hideAnimated:NO];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] mallProductTypeWithDictionary:responseObject];
            [self requestProSubTypeAndShopsWithHeader:YES];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"商品分类失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestProSubTypeAndShopsWithHeader:(BOOL)isHeader {
    NSInteger startIndex = isHeader ? 0 : self.curSubProType.shop_list.count;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(self.curSubProType.typeId) forKey:@"product_type_id"];
    [pars setObject:@(startIndex) forKey:@"index"];
    [pars setObject:@(kRequestShopListSize) forKey:@"size"];
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiProductSubtype] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求二级分类列表返回：%@", responseObject);
        [self collectionViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self.curSubProType proTypeItemWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求二级分类列表失败：%@", error);
        [self collectionViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
        [self refreshWholeView];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

- (KABMallProductType *)proType {
    return [KABModel sharedInstance].mallProductType;
}

- (KABMallProTypeItem *)curSubProType {
    if (self.selProTypeIndex < self.proType.product_type_list.count) {
        return self.proType.product_type_list[self.selProTypeIndex];
    }
    return self.proType.product_type_list.firstObject;
}

@end
